package com.cff.springbootwork.activiti.service;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.cff.springbootwork.activiti.dao.ProductMapper;
import com.cff.springbootwork.activiti.domain.ProductTask;
import com.cff.springbootwork.activiti.domain.UserInfo;

@Service
public class ProductService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	ProductMapper productMapper;

	@Autowired
	UserInfoService appUserService;

	/**
	 * 产生工作流
	 * 
	 * @param userTask
	 * @param userid
	 */
	public void genTask(ProductTask userTask, String userid) {
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("productAdvice");
		Task tmp = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId())
				.singleResult();

		userTask.setInstanceId(processInstance.getProcessInstanceId());
		tmp.setAssignee(userid);
		taskService.complete(tmp.getId());

		userTask.setUserName(userid);
		productMapper.save(userTask);
	}

	/**
	 * 获取提交的工作
	 * 
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public List<ProductTask> applyList(String userid) throws Exception {
		List<ProductTask> tasks = productMapper.getUserTask(userid);
		return tasks;
	}

	/**
	 * 获取待处理的工作
	 * 
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public List<ProductTask> waitList(String userid) throws Exception {
		String userType = findTaskType(userid);
		logger.info("准备查询userType为{}的任务", userType);
		List<Task> tasks = taskService.createTaskQuery().taskName(userType).orderByTaskCreateTime().asc().list();
		List<ProductTask> utasks = new ArrayList<ProductTask>();
		for (int i = 0; i < tasks.size(); i++) {
			ProductTask userTaskTmp = productMapper.getUserTaskByInstanceId(tasks.get(i).getProcessInstanceId());
			if (userTaskTmp != null) {
				userTaskTmp.setTaskId(tasks.get(i).getId());
				utasks.add(userTaskTmp);
			}
		}

		return utasks;
	}

	/**
	 * 工作流流转
	 * 
	 * @param taskid
	 * @param processid
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	public synchronized Boolean processCommit(String taskid, String instanceId, String userid) throws Exception {
		logger.info("审批taskid：{},instanceId:{}", taskid, instanceId);
		try {
			ProductTask userTask = productMapper.getUserTaskByInstanceId(instanceId);
			taskService.complete(taskid);
			userTask.setCurviewer(userid);
			productMapper.updateStatus(userTask);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 根据用户类型获取任务名称
	 * 
	 * @param userId
	 * @return
	 */
	public String findTaskType(String userId) {
		UserInfo appUser = appUserService.getUserInfoByUserName(userId);
		String userType = appUser.getUserType();
		if (userType == null)
			return null;
		if (!StringUtils.isEmpty(userType)) {
			if ("2001".equals(userType)) {
				return "CustomerServiceApproval";
			} else if ("0000".equals(userType)) {
				return "ManagerApproval";
			} else {
				return "commit";
			}
		}
		return null;
	}

	/**
	 * 获取处理过的任务
	 * 
	 * @param userid
	 * @return
	 */
	public List<ProductTask> manageList(String userid) {
		List<ProductTask> utasks = productMapper.getUserTaskByCurrentViwer(userid);

		return utasks;
	}
}
